﻿using AutoMapper;
using MediatR;
using Reporting.API.Application.CommandHandler.InvoiceManagements;
using Reporting.API.Application.Commands.Ticketmanagements;
using Reporting.Errorcode;
using Reporting.Errorcode.ErrorCode;
using Reporting.Infrastructure.Interfaces.Ticketmanagements;

namespace Reporting.API.Application.CommandHandler.Ticketmanagements
{
    public class UpdateTicketmanagementCommandHandler : IRequestHandler<UpdateTicketmanagementCommand, ApiResult>
    {
        private readonly ITicketmanagementRepository _ticketmanagementRepository;
        private readonly IMapper _mapper;
        private readonly ILogger<UpdateTicketmanagementCommandHandler> _logger;

        public UpdateTicketmanagementCommandHandler(ILogger<UpdateTicketmanagementCommandHandler> logger, IMapper mapper, ITicketmanagementRepository ticketmanagementRepository)
        {
            _logger = logger;
            _mapper = mapper;
            _ticketmanagementRepository = ticketmanagementRepository;
        }

        public async Task<ApiResult> Handle(UpdateTicketmanagementCommand request, CancellationToken cancellationToken)
        {
            try
            {
                // id查询开票
                var Ticketmanagements = await _ticketmanagementRepository.GetAsync(x => x.Ticketmanagementid == request.Ticketmanagementid);

                if (Ticketmanagements == null)
                {
                    return ApiResult.Fail("修改当前数据不存在", StatusCodeEnum.BadRequest);
                }


                // 更新开票
                var InvoiceManagementresult = _mapper.Map(request, Ticketmanagements);
                await _ticketmanagementRepository.UpdateAsync(InvoiceManagementresult);


                return ApiResult.Success(StatusCodeEnum.Success);


            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "修改发票修改失败");
                throw;
            };
        }
    }
}
